﻿using System;
using System.Web.Mvc;

namespace ValidationFramework.Web.MVC.Extensions
{
	public static class FormValidatedExtensions
	{
		// constructor
		public static IDisposable FormValidated(this HtmlHelper helper, string formId)
		{
			var builder = new TagBuilder("form");
			builder.Attributes["action"] = helper.ViewContext.HttpContext.Request.Url.ToString();
			builder.Attributes["method"] = "post";
			builder.Attributes["id"] = formId;
			helper.ViewContext.HttpContext.Response.Write(builder.ToString(TagRenderMode.StartTag));

			var script = ClientValidation.GenerateScripts(formId, helper.ViewContext.ViewData.Model.GetType());
			return new ValidatedFormDisposable(helper.ViewContext.HttpContext.Response, script);
		}

		// overloads
		public static IDisposable FormValidated(this HtmlHelper helper)
		{
			return FormValidated(helper, Guid.NewGuid().ToString());
		}
	}
}
